/*
 * Tencent is pleased to support the open source community by making QMUI_Android available.
 *
 * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the MIT License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.eostoken.eos_wallet.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.eostoken.eos_wallet.MainActivity;
import com.eostoken.eos_wallet.bean.AppVersionBean;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.net.common.NetWorkManager;
import com.eostoken.eos_wallet.net.common.RxSubscriber;
import com.eostoken.eos_wallet.utils.AppDataUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.google.gson.JsonObject;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * @author cginechen
 * @date 2016-12-08
 */

public class LauncherActivity extends Activity {

    private static final int PERMISSIONS_REQUEST_CODE = 10;
    //    private Dialog updateDialog;
//    private String url;
    private boolean isPermissions = false;
    private final static int TO_ACTIVITY = 1001;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (TO_ACTIVITY == msg.what) {
                if (isPermissions)
                    doAfterPermissionsGranted();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        BarUtils.transparentStatusBar(this);
        BarUtils.setStatusBarVisibility(this, true);
//        getVersion();
        if (allPermissionsGranted()) {
            isPermissions = true;
            handler.sendEmptyMessage(TO_ACTIVITY);
        } else {
            ActivityCompat.requestPermissions(this, PermissionConstants.getPermissions(PermissionConstants.STORAGE), PERMISSIONS_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            if (allPermissionsGranted()) {
                isPermissions = true;
                handler.sendEmptyMessage(TO_ACTIVITY);
//                doAfterPermissionsGranted();
            } else {
                Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }


    private void doAfterPermissionsGranted() {
        String mCurrentAccountName = WalletUtils.getCurrentAccountName();
        Intent intent;
        if (ObjectUtils.isEmpty(mCurrentAccountName)) {
            intent = new Intent(this, AddWalletActivity.class);
            intent.putExtra("isMain", true);
        } else {
            intent = new Intent(this, MainActivity.class);
        }
        ActivityUtils.startActivity(intent);
        finish();
    }


    private boolean allPermissionsGranted() {
        for (String permission : PermissionConstants.getPermissions(PermissionConstants.STORAGE)) {
            if (ContextCompat.checkSelfPermission(getBaseContext(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

//    private void getVersion() {
//        NetWorkManager.getRequest().getVersion("1", "1")
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new RxSubscriber<JsonObject>(LauncherActivity.this, false) {
//                    @Override
//                    public void onFail(String failMsg) {
//                    }
//
//                    @Override
//                    public void onSuccess(JsonObject data) {
//                        if (ObjectUtils.isNotEmpty(data)) {
//                            AppVersionBean appVersionBean = GsonUtils.fromJson(data.toString(), AppVersionBean.class);
//                            if (appVersionBean.getCode() > 0) {
//                            } else {
//                                AppVersionBean.DataBean dataBean = appVersionBean.getData();
//                                if (dataBean != null) {
//                                    String versioncode = dataBean.getVersioncode();
//                                    if (ObjectUtils.isNotEmpty(versioncode))
//                                        if (Integer.parseInt(versioncode) > AppUtils.getAppVersionCode()) {
//                                            url = dataBean.getDownload();
//                                            String versiondes = dataBean.getVersiondes();
//                                            updateDialog = DialogHelper.showUpdateDialog(LauncherActivity.this, versiondes, listener);
//                                            return;
//                                        }
//                                }
//                            }
//                            handler.sendEmptyMessage(TO_ACTIVITY);
//                        }
//                    }
//                });
//    }
//
//    View.OnClickListener listener = new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            if (updateDialog != null) {
//                updateDialog.dismiss();
//            }
//            AppDataUtils.downloadApk(LauncherActivity.this, url, "MangoWallet");
//        }
//    };
}
